const { userService } = require('../../services/index');

Page({
  data: {
    username: '',
    password: '',
    nickname: '',
    invitationCode: '',
    isLoading: false
  },

  onUsernameChange(e) {
    this.setData({ username: e.detail });
  },

  onPasswordChange(e) {
    this.setData({ password: e.detail });
  },

  onNicknameChange(e) {
    this.setData({ nickname: e.detail });
  },

  onInvitationCodeChange(e) {
    this.setData({ invitationCode: e.detail });
  },

  async handleRegister() {
    const { username, password, nickname, invitationCode } = this.data;
    
    // 表单验证
    if (!username || !password || !nickname || !invitationCode) {
      this.showNotify('请填写完整信息');
      return;
    }
    
    this.setData({ isLoading: true });
    
    try {
      // 调用注册API
      const res = await userService.register({
        username,
        password,
        nickname,
        invitationCode
      });
      
      // 注册成功，自动登录并跳转
      const loginRes = await userService.login({
        username,
        password
      });
      
      getApp().login(loginRes.userInfo, loginRes.token);
      
      // 检查是否有情侣关系
      if (getApp().globalData.coupleInfo) {
        wx.switchTab({
          url: '/pages/index/index'
        });
      } else {
        wx.redirectTo({
          url: '/pages/couple/bind'
        });
      }
      
    } catch (error) {
      // 注册失败，显示错误信息
      this.showNotify(error.message || '注册失败');
    } finally {
      this.setData({ isLoading: false });
    }
  },

  navToLogin() {
    wx.redirectTo({
      url: '/pages/login/index'
    });
  },

  showNotify(message) {
    this.selectComponent('#notify').show({
      message,
      duration: 2000,
      color: '#fff',
      background: '#FF6B8B'
    });
  },

  showDialog(title, message, callback) {
    this.selectComponent('#dialog').confirm({
      title,
      message,
      confirmButtonText: '确定',
      showCancelButton: false
    }).then(() => {
      callback && callback();
    });
  }
});